import json
import subprocess

from channels.generic.websocket import JsonWebsocketConsumer

from utils.rest.decorator import action_name


@action_name('ping命令')
class PingTimeInfoConsumer(JsonWebsocketConsumer):

    def websocket_connect(self, event):
        self.accept()

    def websocket_receive(self, event):
        url = json.loads(event.get('text')).get('data')
        if url != '':
            self.url = url
            cmd = 'ping ' + url
            p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            self.p = p
            self.pid = p.pid
            if p.poll() is None and url != '':
                line = p.stdout.readline()
                line = line.strip()
                self.send_json({
                    'info': str(line, 'utf-8')
                })
        else:
            if self.p.poll() is None and url == '':
                line = self.p.stdout.readline()
                line = line.strip()
                self.send_json({
                    'info': str(line, 'utf-8')
                })

    def websocket_disconnect(self, message):
        cmd = 'kill -9 ' + str(self.pid)
        subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        super(PingTimeInfoConsumer, self).websocket_disconnect(message)


